import React from "react"
import { Route, Switch } from "react-router-dom"

// A special wrapper for <Route> that knows how to
// handle "sub"-routes by passing them in a `routes`
// prop to the component it renders.
const RouteWithSubRoutes = (route) => (
  <Route
    path={route.path}
    render={(props) => (
      // pass the sub-routes down to keep nesting
      <route.component {...props} routes={route.routes} />
    )}
  >
    {route.children}
  </Route>
)

const FlatRoutes: React.FC<{ routes: any }> = ({ routes }) => (
  <Switch>
    {routes.map((props) => (
      <RouteWithSubRoutes {...props} key={props.path}>
        {props?.routes?.length ? <FlatRoutes routes={props.routes} /> : null}
      </RouteWithSubRoutes>
    ))}
  </Switch>
)

export default FlatRoutes
